<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Category_Controllers_Category extends Gio_Core_Controller
{
	private $_defaultModule = 'news';
	
	/* ########################### Frontend Action ###########################*/
	
    /* ########################### Backend Action ############################*/
	
	public function activateAction()
	{
		$this->setNoRender();
		$this->disableLayout();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			return;
		}
		$response = 'RESULT_NOT_OK';
		$categoryId = $request->getPost('category_id');
		$category = Modules_Category_Services_Category::getById($categoryId);
		
		if (null == $category){
			$this->getResponse()->setBody($response);
			return;	
		}
		
		$act = $request->getPost('act');
		switch ($act) {
			case 'activate':
				$status = 'active';
				break;
			case 'deactivate':
				$status = 'inactive';
				break;
		}
		$category['status'] = $status;
		$response = 'RESULT_OK';
		Modules_Category_Services_Category::activate($category);
		$this->getResponse()->setBody($response);
	}
	
	public function addAction()
	{
		$request = $this->getRequest();
		$this->view->defaultModule = $this->_defaultModule;
		
		$sourceId       = $request->getParam('source_id');
		$sourceCategory = (null == $sourceId) ? null : Modules_Category_Services_Category::getById($sourceId);
		
		$this->view->sourceCategory = $sourceCategory;
		
		$this->view->lang		   = $request->getParam('lang');
		
		$conn		= Gio_Db_Connection::getConnection();
		$categoryDao = new Modules_Category_Models_Mysql_Category();
		$categoryDao->setConnection($conn);
		$this->view->categoryDao = $categoryDao;
		
		if ($request->isPost()) {
			$user = Gio_Core_Session::getUser();

			$categoryData = $request->getPost('category');
			$categoryData = Modules_Category_Services_Category::validate($categoryData);
			
			if (isset($categoryData['messages_error']) && $categoryData['messages_error']) {
				$this->view->errorMessages = $categoryData['messages'];
				$this->view->categoryData = $categoryData;
				return;
			}
			
			$parentCategory = null;
			if ($categoryData['parent_id']) {
				$parentCategory = Modules_Category_Services_Category::getById($categoryData['parent_id']);
			}
			
			$path = ($parentCategory && $parentCategory['category_path']) 
								? $parentCategory['category_path'] . '/' . $categoryData['slug'] : $categoryData['slug'];
			
			$category = array(
					'name' 	   	    => $this->view->STRING->escape($categoryData['name']),
					'slug'  	    => $this->view->STRING->escape($categoryData['slug']),
					'category_path'	=> $this->view->STRING->escape($path),
					'meta'  	    => $this->view->STRING->escape($categoryData['meta']),
					'status'	    => $this->view->STRING->escape($categoryData['status']),
					'module_id'	    => $this->view->STRING->escape($categoryData['module_id']),
					'parent_id'	    => $this->view->STRING->escape($categoryData['parent_id']),
					'language'	    => $this->view->STRING->escape($categoryData['language']),
					'status'	    => $this->view->STRING->escape($categoryData['status']),
					'created_date'  => date('Y-m-d H:i:s'),
					'modified_date' => date('Y-m-d H:i:s'),
					'user_id'	    => $user['user_id']	
			);
			
			$sourceItem = isset($categoryData['source_item']) 
								? $categoryData['source_item'] : null;
			$categoryId = Modules_Category_Services_Category::add($category, $sourceItem);
						
			Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('category_actions_add_success'));
			$this->redirect($this->view->url('category_category_add'));
		}
	}
	
	public function deleteAction()
	{
		$this->setNoRender();
		$this->disableLayout();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			return;
		}
		$categoryId = $request->getPost('category_id');
		$category = Modules_Category_Services_Category::getById($categoryId);
		
		$condition = array('parent_id' => $categoryId);
		if (null == $category || Modules_Category_Services_Category::count($condition) > 0){
			$this->getResponse()->setBody('RESULT_NOT_OK');
			return;	
		}
		
		/**
		 * Delete category
		 */
		Modules_Category_Services_Category::delete($category);
		$this->getResponse()->setBody('RESULT_OK');
	}
	
	public function editAction()
	{
		$request = $this->getRequest();
		$this->view->defaultModule = $this->_defaultModule;
		
		$categoryId = $request->getParam('category_id');
		$category = Modules_Category_Services_Category::getById($categoryId);
		if (null == $category) {
			throw new Exception('Data not found');
		}
		$oldCategory = $category;
		$this->view->categoryData = $category;
		
		$sourceCategory = Modules_Category_Services_Category::getSource($category);
		$this->view->sourceCategory = $sourceCategory;

		if ($request->isPost()) {
			$categoryData = $request->getPost('category');
			$categoryData['language']  = $category['language'];
			$categoryData['module_id'] = $category['module_id'];
			$categoryData['language']  = $category['language'];
			
			$categoryData = Modules_Category_Services_Category::validate($categoryData);
			
			if (isset($categoryData['messages_error']) && $categoryData['messages_error']) {
				$this->view->errorMessages = $categoryData['messages'];
				$categoryData['category_id'] = $categoryId;
				$this->view->categoryData = $categoryData;
				return;
			}
			
			$parentId = $category['parent_id'];
			$parentCategory = null;
			if ($parentId) {
				$parentCategory = Modules_Category_Services_Category::getById($parentId);
			}
			
			$path = ($parentCategory && $parentCategory['category_path']) 
							? $parentCategory['category_path'] . '/' . $categoryData['slug'] : $categoryData['slug'];
			
			$category = array(
					'category_id'   => $categoryId,
					'name' 	   	    => $this->view->STRING->escape($categoryData['name']),
					'slug' 	   	    => $this->view->STRING->escape($categoryData['slug']),
					'category_path'	=> $this->view->STRING->escape($path),
					'meta'  	    => $this->view->STRING->escape($categoryData['meta']),
					'module_id'	    => $this->view->STRING->escape($categoryData['module_id']),
					'parent_id'	    => $this->view->STRING->escape($categoryData['parent_id']),
					'language'	    => $this->view->STRING->escape($categoryData['language']),
					'created_date'  => $this->view->STRING->escape($oldCategory['created_date']),
					'modified_date' => date('Y-m-d H:i:s'),
					'status'	    => $this->view->STRING->escape($categoryData['status']),
					'user_id'       => $oldCategory['user_id']
			);
			$sourceItem = isset($categoryData['source_item']) 
								? $categoryData['source_item'] : null;
			
			/**
			 * Get parent category
			 */
			if ($category['parent_id'] == $parentId) {
				/**
				 * User do NOT change the parent category value
				 */
				Modules_Category_Services_Category::update($category, $sourceItem);
			} else {
				/**
				 * User changed parent category
				 */
				Modules_Category_Services_Category::delete($oldCategory);
				Modules_Category_Services_Category::add($category, $sourceItem);
				Modules_Category_Services_Category::updateParents($category['language'], $category['module_id']);
			}
			
			Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('category_actions_edit_success'));
			$this->redirect($this->view->url('category_category_edit', $category));
		}
	}
	
	/**
	 * List categories
	 * 
	 * @return void
	 */
	public function listAction() 
	{
		$request = $this->getRequest();
		$moduleId = $request->getParam('module_id', $this->_defaultModule);
		$this->view->defaultModule = $moduleId;
	
		$lang       = $request->getParam('lang');

		
		$categories = Modules_Category_Services_Category::getTree($lang, $moduleId);
		
		$this->view->categories = $categories;
		$this->view->categoryDao = new Modules_Category_Models_Mysql_Category();
		$this->view->lang = $lang;
	} 
	
	public function orderAction()
	{
		$this->setNoRender();
		$this->disableLayout();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			$this->getResponse()->setBody('RESULT_NOT_OK');
			return;
		}
		$response = 'RESULT_NOT_OK';
		$data = $request->getPost('data');
		$json = new Services_JSON();
		$data = $json->decode($data);
		
		foreach ($data as $category) {
			Modules_Category_Services_Category::updateOrder(array(
				'category_id' => $category->id,
				'parent_id'   => $category->parent_id,
				'left_id'     => $category->left_id,
				'right_id'    => $category->right_id,
			));
		}
			
		$this->getResponse()->setBody('RESULT_OK');
	}
}